var nowDate = getDay(0);
var shopcode = sessionStorage.getItem("shopcode");
var userId = sessionStorage.getItem("userId");
var everyId = GetQueryString('everyId');
var _config ;
$.ajax({
	type : "post",
	data:JSON.stringify({"pageUrl":location.href.replace(/\\&/g,'%26'),"corp":sessionStorage.getItem("corp")}),
	contentType: "application/json; charset=utf-8",
	async: false,
	url : "../../dingding/getconfig",
	dataType : "json",
	success : function(suc) {
		console.log(suc);
		_config = suc.config;
	}
}); 
dd.config({
	agentId : _config.agentid,
	corpId : _config.corpId,
	timeStamp : _config.timeStamp,
	nonceStr : _config.nonceStr,
	signature : _config.signature,
	jsApiList : [ 'runtime.info','biz.util.uploadImage','biz.contact.complexPicker' ]
});
function ICalendarClick(){
//	onload()
}
$(document).ready(function(){
	$('#name').text(sessionStorage.getItem("name"));
	getSiji_qiandao_item();
	$('#saveButton').on('click',saveInfo);
});

//获取门店待办信息
function getSiji_qiandao_item(){
	showloading();
	var sendData = {};
	sendData.flag = 0;
	$.ajax({
		url: "getHuodong_jiancha_jd_item"
		,type:'post'
		,dataType:'json'
//		,async: false
		,contentType: "application/json; charset=utf-8"
		,data:JSON.stringify(sendData) 
		,success: function(res){
			console.log(res)
			try {
				if(res.success){
					var data = res.data;
					$('#item_div').empty();
					if(data != undefined && data.length > 0){
						addItem(data);
					}
				}else{
					layer.msg(res.message);
				}
			} catch (e) {
				console.log(e)
			} finally{
				hideloading();
			}
		}
    });
}
function addItem(jsonparse){
	for(var i = 0 ;i<jsonparse.length;i++){
		var imgStr = '';
		if (jsonparse[i].isphoto == '0') {
			imgStr = '		<div class="widget-box add_mar_tb7p">'
					+'			<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_bor_tbgrey">'				
					+'				<h5><i class="iconfont">&#xe600;</i>&nbsp;图片上传</h5><span class="red"></span>'						  
					+'				<div class="widget-toolbar no-border" style="margin-top: 5px"  onclick="openphoto('+jsonparse[i].id+')">'
					+'					<img src="../../genius/style/mobile_page/assets/images/photo.png" />'
					+'				</div>'
					+'			</div>'				
					+'			<div class="widget-body zhediebox1">'					
					+'				<div class="widget-main pd_div" id="paizhapoUrl'+jsonparse[i].id+'" >'
					+'					<div class="clearfix"></div>'						
					+'				</div>'						
					+'			</div>'					
					+'		</div>';
		}
		var thenum = $('div[itemDiv]').length;
		$('#item_div').append('<div class="col_box" itemDiv="'+jsonparse[i].id+'">'
				+'<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_mar_tb7p">'
				+'<h5 id="wentishuomingTitle" class="black">检查条款'+(thenum+1)+'</h5>'
//				+'<div deleteIndex="'+thenum+'" class="bt_delete bg_orange">删除</div><div class="clearfix"></div>'
				+'</div>'
				+'		<div class="widget-box add_mar_tb7p">'
				+'			<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_bor_tbgrey">'
				+'				<h5><i class="iconfont">&#xe600;</i>&nbsp;条款</h5><span class="red" bitian></span>'
				+'				<div class="pull-right add_bor_none" style="width: 70%;margin-right: 2%; color:#474747; line-height:26px;">'+jsonparse[i].name+'</div>'
				+'			</div>'
				+'		</div>'
				+'		<div class="widget-box add_mar_tb7p">'
				+'			<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_bor_tbgrey">'
				+'				<h5><i class="iconfont">&#xe600;</i>&nbsp;检查标准</h5><span class="red" bitian></span>'
				+'				<div class="pull-right add_bor_none" style="width: 70%;margin-right: 2%; color:#474747; line-height:26px;">'+jsonparse[i].biaozhun+'</div>'
				+'			</div>'
				+'		</div>'
				+'		<div class="widget-box add_mar_tb7p">'
				+'			<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_bor_tbgrey">'
				+'				<h5><i class="iconfont">&#xe600;</i>&nbsp;满分</h5><span class="red" bitian>*</span>'
				+'				<input type="tel" placeholder="请输入满分" readonly jsonKey="maxScore" value="'+jsonparse[i].maxScore+'"  class="pull-right add_bor_none" style="width: 70%;margin-right: 2%"/>'
				+'			</div>'
				+'		</div>'
				+'		<div class="widget-box add_mar_tb7p">'
				+'			<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_bor_tbgrey">'
				+'				<h5><i class="iconfont">&#xe600;</i>&nbsp;得分</h5><span class="red" bitian>*</span>'
				+'				<input type="tel" placeholder="请输入得分" jsonKey="score" autocomplete="off"   class="pull-right add_bor_none" style="width: 70%;margin-right: 2%"/>'
				+'			</div>'
				+'		</div>'
				+'		<div class="widget-box add_mar_tb7p">'
				+'			<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_bor_tbgrey">'
				+'				<h5><i class="iconfont">&#xe600;</i>&nbsp;备注</h5><span class="red" bitian></span>'
				+'				<input type="text" placeholder="请输入备注" jsonKey="remark" autocomplete="off"   class="pull-right add_bor_none" style="width: 70%;margin-right: 2%"/>'
				+'			</div>'
				+'		</div>'
//				+'		<div class="widget-box add_mar_tb7p">'
//				+'			<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_bor_tbgrey">'
//				+'				<h5><i class="iconfont">&#xe61e;</i>&nbsp;发送到人</h5><span class="red"></span>'
//				+'				<input type="text" id="sendusername'+thenum+'" readonly="readonly" value="'+jsonparse[i].sendusername+'" onclick="openDingdingUser('+thenum+')" placeholder="请选择" jsonKey="sendusername" autocomplete="off"   class="pull-right add_bor_none" style="width: 70%;margin-right: 2%"/>'
//				+'				<input type="hidden" id="senduser'+thenum+'" value="'+jsonparse[i].senduser+'" jsonKey="senduser"/>'
//				+'			</div>'
//				+'		</div>'
				+imgStr
				+'<input type="hidden" value="'+jsonparse[i].id+'" jsonKey="itemid"/>'
				+'<input type="hidden" value="'+jsonparse[i].name+'" jsonKey="itemname"/>'
				+'<input type="hidden" value="'+jsonparse[i].biaozhun+'" jsonKey="itembiaozhun"/>'
//				+'<div editIndex="'+thenum+'" class="bt_delete bg_blue">编辑</div><div class="clearfix"></div>'					
				+'</div>');
	
	}
}
function addoperation(){
//	$('#addButton').append(
//		'<div class="submit_button w94 bg_red">'
//	   +'<span  style="display:inline-block; width:16px; height:16px!important; line-height:14px!important; font-weight:600; font-size:15px; text-align:center; border:1px #fff solid; border-radius:10px; color:#fff!important;">+</span>'
//  	   +'新增问题反馈</div>'
//	);
	
	 $('#saveButton').append('<div class="submit_button w94">提交</div>');
}
//完成待办
function saveInfo(){
	showloading();
	try {
		var imgStr = "";
		var sendData = {};
		var insertArray = [];
		var checkFlag = true;
		var maxScore=0,score=0;
		$('div[itemDiv]').each(function(i,obj){
			if(checkFlag){
				var insertJson = {};
				$(obj).find('[jsonKey]').each(function(j,el){
					if($(el).parent().find('span[bitian]').text() == '*' && $(el).val() == ''){
						alert($(el).parent().find('h5').text()+"为必填项");
						checkFlag = false;
						return false;
					}else{
						var key = $(el).attr('jsonKey');
						if(key == 'score'){
							if(isNaN(Number($(el).val()))){
								alert($(el).parent().find('h5').text()+"不是合法的数字");
								checkFlag = false;
								return false;
							}else{
								score += Number($(el).val());
							}
							
						}else if(key == 'maxScore'){
							maxScore += Number($(el).val());
						}
						insertJson[key] = $(el).val();
						
						//console.log(insertJson);
						key = null;
					}
				});
				if(checkFlag){
					//设置图片
					var img = [];
					$(obj).find('img[daibanimg]').each(function(j,el){
						img.push($(el).attr('src'));
					});
					insertJson.imgurl = img;
					
				}
				if(Number(insertJson.maxScore) < Number(insertJson.score)){
					alert("得分不能超过满分");
					checkFlag = false;
				}
				insertJson.everyId = everyId;
				insertJson.lrr = userId;
				insertJson.shopcode = shopcode;
				insertArray.push(insertJson);
			}else{
				return false;
			}
		});
		if(checkFlag && insertArray.length > 0){
			sendData.dataArray = insertArray;
			sendData.maxScore = maxScore;
			sendData.score = score;
			sendData.id = everyId;
			sendData.flag = 1;
			sendData.shopcode = shopcode;
			sendData.pjId = sessionStorage.getItem("mobile");
			sendData.pingjiaUserName = sessionStorage.getItem("name");
//			sendData.pingjiaUserName = sessionStorage.getItem("name");
			sendData.pingjiaUser = sessionStorage.getItem("userId");
			$.ajax({
				url: "replaceHuodong_jiancha_jd_every_item"
				,type:'post'
				,dataType:'json'
				,async: false
				,contentType: "application/json; charset=utf-8"
				,data:JSON.stringify(sendData) 
				,success: function(res){
					console.log(res)
					if(res.success){
						layer.alert("检查成功");
					}else{
						hideloading();
						layer.alert(res.message);
					}
				}
		    });
		}
/*		console.log(insertArray.length);*/
	} catch (e) {
		console.log(e)
	} finally{
		hideloading();
	}
}
//打开钉钉拍照
function openphoto(index){
	
	dd.ready(function(){
		dd.biz.util.uploadImage({
		    compression: false,//(是否压缩，默认为true)
		    quality: 100, // 图片压缩质量, 
		    resize: 100, // 图片缩放率
		    stickers: {   // 水印信息
		        time: nowDate,
		        username: sessionStorage.getItem("name")
		    },
		    onSuccess : function(result) {
				$('#paizhapoUrl'+index+' .clearfix').remove()
				$('#paizhapoUrl'+index).append('<div class="wig_img">'
						+'<div class="img_box">'
						+'<img daibanimg alt="100x100" src="'+result[0]+'" onclick="showAllPic(\''+result[0]+'\')"/>'
						+'<img class="close_b" src="../../genius/style/mobile_page/assets/images/close.png" onclick="deletePhoto(this)">'
						+'</div>'
						+'</div>');
				$('#paizhapoUrl'+index).append('<div class="clearfix"></div>');
		    },
		    onFail : function(err) {}
		});
	});
	dd.error(function(err) {
		alert(JSON.stringify(err));
		
//		alert('dd error: ' + JSON.stringify(err));
	});
}	
//删除图片
function deletePhoto(obj){
	dd.device.notification.confirm({
	    message: "删除图片吗",
	    title: "提示",
	    buttonLabels: ['是', '否'],
	    onSuccess : function(result) {
	    	if(result.buttonIndex == '0'){
	    		var index = $(obj).parent().parent().index();
	    		$(obj).parent().parent().remove();
	    		photoUrl.splice(index,1);
	    	}
	        
	    },
	    onFail : function(err) {}
	});
	 
}
//预览图片
function showAllPic(imgOne){
	dd.biz.util.previewImage({
		urls: imgOne.split(','),//图片地址列表
		current: imgOne,//当前显示的图片链接
		onSuccess : function(result) {
			/**/
		},
		onFail : function(err) {}
	})
}